﻿using FineUI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.Core.Util;
using ZHDJ.Data.Models.JoinParty;
using ZHDJ.JoinParty.BLL;

namespace JoinParty.admin.FlowStep
{
    public partial class AppointCultivateContacts : PageBase
    {
        public string ID
        {
            get
            {
                return GetQueryIntValue("id");
            }
        }

        /// <summary>
        /// 联系人类型
        /// </summary>
        public int ContactType
        {
            get
            {
                var re = 0;
                var type = GetQueryIntValue("type");
                if (type != "")
                {
                    re = int.Parse(type);
                }
                return re;
            }
        }
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "";
            }
        }

        #endregion
        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        private void BindData()
        {
        }
        private void LoadData(string IsSave = "")
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            if (!string.IsNullOrEmpty(this.CurrentStandID))
            {
                var oModel = DB.PartyJoinLinkExamples.Find(this.CurrentStandID);
                DataSet ds = partyJoinContact.GetGridData(oModel.AppllicationID, ContactType);

                rptContacts.DataSource = ds;
                rptContacts.DataBind();

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    string LoginID = string.Empty;
                    string UserName = string.Empty;
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        string id = row["LoginID"] == null ? "" : row["LoginID"].ToString();
                        string name = row["UserName"] == null ? "" : row["UserName"].ToString();
                        LoginID = LoginID + "," + id;
                        UserName = UserName + "," + name;
                        this.dtTime.Text = Convert.ToDateTime(row["ContactTime"]).ToString("yyyy-MM-dd");
                    }
                    this.ppUser.Value = LoginID.Trim(',');
                    this.ppUser.Text = UserName.Trim(',');
                }
                else
                {
                    this.dtTime.Text = Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd");
                }
            }
            this.btnSaveClose.Hidden = true;

            if (ContactType == 1)
            {
                dtTime.Hidden = true;
                ppUser.Label = "指定入党介绍人";
                ppUser.WindinsTitle = ppUser.EmptyText = "选择入党介绍人";
                lbMsg.Label = "";
            }


            //页面只读显示
            if (this.ReadOnly.Trim() == "1")
            {
                this.btnSubmit.Hidden = true;
                this.btnEnSure.Enabled = false;

                this.hdDelete.Value = "1";
                hdModifyAdmin.Value = "0";
                if (IsAdmin)
                {
                    btnSubmit.Hidden = true;
                    this.btnSaveClose.Hidden = false;
                    this.btnEnSure.Enabled = true;
                    this.hdDelete.Value = "0";
                }
            }

            //页面只读显示
            if (this.ReadOnly.Trim() == "1")
            {
                this.btnSubmit.Visible = false;
                if (IsJoinPartyAdmin)
                {
                    this.btnSaveClose.Visible = true;
                }
            }
        }



        private void SaveData(PartyJoinLinkExample oModel, bool isClose, bool AdminSave = false)
        {
            string Message = "";///接收处理流程反馈的消息主要判断当前步骤是否已审核过

            bool bResult = false;

            oModel.Remark = "指定培养联系人！";
            if (ContactType == 1)
            {
                oModel.Remark = "指定入党介绍人！";
            }

            oModel.HandleUserID = this.CurrentUser.LoginID;
            oModel.HandleUserName = this.CurrentUser.UserName;
            oModel.HandleTime = DateTime.Now;
            oModel.Status = (int)Enum_FlowStanceStatus.通过;

            bResult = ProcesUtil.ApprovalProcesStep(oModel, out Message);
            if (bResult)
            {
                #region 发送短信和待办给联系人
                ///获取联系人电话号码
                //DataSet ds = partyJoinContact.GetContactMsg(oModel.AppllicationID);
                //if (ds.Tables[0].Rows.Count > 0)
                //{
                #region 发送短信
                //string allmobileNo = "";
                //foreach (DataRow dr in ds.Tables[0].Rows)
                //{
                //    allmobileNo += dr["MobileNo"].ToString() + ",";
                //}
                ////去除最后一个逗号
                //allmobileNo = allmobileNo.Substring(0, allmobileNo.Length - 1);
                //string[] Mobile = new string[] { allmobileNo };
                //string Content = ModuleConfigs.ContactMssContent;

                //PartyJoinApplycation paj = new PartyJoinApplycation();
                //paj.AppllicationID = oModel.AppllicationID;
                //paj.Load();

                //OrgMember om = new OrgMember();
                //om.LoginID = paj.LoginID;
                //om.Load();
                //string AppllicationName = om.UserName;
                //PartySMSLibrary.SendMassage(Mobile.ToList(), string.Format("" + Content + "", AppllicationName), "入党联系人");
                #endregion
                #region 推送联系人待办信息
                //foreach (DataRow dr in ds.Tables[0].Rows)
                //{
                //    PartyTask.AddTask(dr["ID"].ToString(), "入党联系人", "入党联系人", this.CurrentUser.LoginID, new string[] { dr["ContactID"].ToString() },
                //"../../../JoinParty/Module/Audit/AppointCultivateContactsAudit.aspx?RelationID=" + dr["ID"].ToString(), PartyTask.TaskSpecie.Member);
                //}
                #endregion
                //}
                #endregion
            }
            else
            {
                if (Message != "")
                {
                    Alert.Show(Message, String.Empty, ActiveWindow.GetHideReference());
                }
            }
        }
        /// <summary>
        /// 确定指定联系人
        /// </summary>
        private void SavePartyJoinContact()
        {
            var standMode = DB.PartyJoinLinkExamples.Find(this.CurrentStandID);
            partyJoinContact.DeleteContacts(standMode.AppllicationID, ContactType);
            DataSet ds = partyJoinContact.GetOrgMember(this.ppUser.Value.Trim().Replace("，", ","));
            if (ds != null && ds.Tables.Count > 0)
            {
                ds.Tables[0].Columns.Add("ID");
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    partyJoinContact oModel = new partyJoinContact();
                    oModel.ID = StringHelper.NewID;
                    oModel.AppllicationID = standMode.AppllicationID;
                    oModel.ContactID = row["LoginID"] == null ? "" : row["LoginID"].ToString();
                    oModel.ContactName = row["UserName"] == null ? "" : row["UserName"].ToString();
                    oModel.InParty = row["Post"] == null ? "" : row["Post"].ToString();
                    oModel.Administration = string.Empty;
                    oModel.ContactType = ContactType;
                    if (row["JoinPartyDate"] != null && !string.IsNullOrEmpty(Convert.ToString(row["JoinPartyDate"])))
                        oModel.PartyStanding = (DateTime.Now.Year - Convert.ToDateTime(row["JoinPartyDate"]).Year).ToString();
                    if (!string.IsNullOrEmpty(dtTime.Text))
                    {
                        oModel.ContactTime = Convert.ToDateTime(dtTime.Text);
                    }
                    else { oModel.ContactTime = DateTime.Now; }
                    DB.partyJoinContacta.Add(oModel);
                    if (DB.SaveChanges() > 0)
                    {
                        ds.Tables[0].Rows[i]["ID"] = oModel.ID;
                    }
                }
                this.rptContacts.DataSource = ds;
                this.rptContacts.DataBind();
            }
        }

        #endregion

        #region
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            PartyJoinLinkExample oModel = null;
            if (CheckValue(ref oModel))
            {
                this.SaveData(oModel, true);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                Alert.Show("联系人不能少于一人，也不能多于两人，请确认后提交！", String.Empty);
            }
        }

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            PartyJoinLinkExample oModel = null;
            if (CheckValue(ref oModel))
            {
                SaveData(oModel, true, true);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                Alert.Show("联系人不能少于一人，也不能多于两人，请确认后提交！", String.Empty);
            }
        }
        #endregion
        private bool CheckValue(ref PartyJoinLinkExample oModel)
        {
            oModel = DB.PartyJoinLinkExamples.Find(this.CurrentStandID);
            if (oModel != null)
            {
                DataSet dsA = partyJoinContact.GetGridData(oModel.AppllicationID, ContactType);
                if (dsA.Tables[0].Rows.Count == 0 || dsA.Tables[0].Rows.Count > 2)
                    return false;
                else
                    return true;
            }
            else
                return false;
        }

        private bool CheckValue()
        {
            if (!string.IsNullOrEmpty(this.ppUser.Value.Trim()))
            {
                string[] users = this.ppUser.Value.Trim().Replace("，", ",").Split(',');
                if (users.Length > 2)
                    return false;
                else
                    return true;
            }
            else
                return false;
        }

        protected void btnEnSure_Click(object sender, EventArgs e)
        {
            if (CheckValue())
            {
                SavePartyJoinContact();
            }
            else
                Alert.Show("联系人不能少于一人，也不能多于两人，请重新选择！", String.Empty);
        }

        /// <summary>
        /// 删除指定联系人方法
        /// </summary>
        /// <param name="ID">主键ID</param>
        /// <returns></returns>
        [WebMethod]
        public static bool DeleteContacts(string ID)
        {
            var oModel = DB.partyJoinContacta.FirstOrDefault(p => p.ID == ID);
            DB.partyJoinContacta.Remove(oModel);
            return DB.SaveChanges() > 0;
        }

    }
}